package com.casic.modules.sys.api;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.casic.common.utils.UploadFileUtil;
import com.casic.common.utils.api.ResultInfo;
import com.casic.modules.sys.controller.AbstractController;
import com.casic.modules.sys.entity.SysEnclosureEntity;
import com.casic.modules.sys.entity.SysUserEntity;
import com.casic.modules.sys.service.SysEnclosureService;
import com.casic.modules.sys.shiro.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/file/")
public class ApiFileUploadController extends AbstractController {
    // 本地异常日志记录对象
    private static final Logger logger = LoggerFactory
            .getLogger(ApiFileUploadController.class);

    @Autowired
    private SysEnclosureService sysEnclosureService;
    @Value("${spring.uploadFilePath}")
    private String  path;

    /**
     *  app端上传文件
     * @param request
     * @return
     */
    @RequestMapping(value = "upload" ,method = RequestMethod.POST)
    public JSONObject upload(HttpServletRequest request,@RequestParam("files")List<MultipartFile> files){
        try{
            SysUserEntity sysUserEntity= ShiroUtils.getUserEntity();
            //验证是否登陆
            if(org.springframework.util.StringUtils.isEmpty(sysUserEntity)){
                return ResultInfo.error(ResultInfo.NO_LOGIN);
            }
            logger.debug("上传文件开始！！");
            List<SysEnclosureEntity> sysEnclosureEntityList=UploadFileUtil.apiUploadFile(files,path);
            logger.debug("获取文件数据list！！");
            sysEnclosureEntityList=sysEnclosureService.saveBatch(sysEnclosureEntityList);
            JSONArray data = (JSONArray)  JSONArray.toJSON(sysEnclosureEntityList);
            return ResultInfo.success(data);
        }catch (Exception e) {
            e.printStackTrace();
            return ResultInfo.error( ResultInfo.UPLOAD_FILE_ERROR);
        }
    }
}
